<?php


namespace App\Api\Model;


use EchoPHP\Facades\Db as Db;

class ResumeInfoCompare {
    public function compareDiff($resumeId, $taskId) {
        $fileProfix = config('app.resume_machine_learning.log_file_path') . '/';
        $filePath = 'success/' . floor($resumeId / 2000) . '/' . $resumeId . '_' . $taskId . '.txt.json';
        $dataBeforeStr = @file_get_contents($fileProfix . $filePath);
        echo $fileProfix . $filePath . "<br/>";
        if (empty($dataBeforeStr)) {
            echo '文件不存在';
            exit();
        }
        $dataBeforeStr = strtolower($dataBeforeStr);

        $dataBefore = json_decode($dataBeforeStr, true);

        //获取当前数据库保存的数据
        $dataAfter = [];
        $sql = 'SELECT resumeid,taskid,source FROM UploadResume where resumeid = ? and taskid = ?';
        $var = [$resumeId, $taskId];
        $result = Db::connect('jyrpo')->selectOne($sql, $var);
        $dataAfter = array_merge($dataAfter, $result);

        $sql = 'SELECT company,duty,salary,content,creator,updator,workindustry,workindustrytext, DATE_FORMAT(starttime,\'%Y-%m-%d\') as starttime,DATE_FORMAT(endtime,\'%Y-%m-%d\') as endtime FROM ResumeWork WHERE resumeid = ? order by id';
        $var = [$resumeId];
        $result = Db::connect('jyrpo')->select($sql, $var);
        if (!empty($result)) {
            foreach ($result as $item => &$value) {
                if ($value['starttime'] == '0000-00-00') {
                    $value['starttime'] = '';
                }
                if ($value['endtime'] == '0000-00-00') {
                    $value['endtime'] = '';
                }
            }
            $dataAfter = array_merge($dataAfter, ['workinfo' => $result]);
        }

        $sql = 'SELECT DATE_FORMAT(starttime,\'%Y-%m-%d\') as starttime,DATE_FORMAT(endtime,\'%Y-%m-%d\') as endtime,company,duty,project,content FROM ResumeProject WHERE resumeid = ? order by id';
        $var = [$resumeId];
        $result = Db::connect('jyrpo')->select($sql, $var);
        if (!empty($result)) {
            foreach ($result as $item => &$value) {
                if ($value['starttime'] == '0000-00-00') {
                    $value['starttime'] = '';
                }
                if ($value['endtime'] == '0000-00-00') {
                    $value['endtime'] = '';
                }
            }
            $dataAfter = array_merge($dataAfter, ['projectinfo' => $result]);
        }

        $sql = 'SELECT DATE_FORMAT(starttime,\'%Y-%m-%d\') as starttime,DATE_FORMAT(endtime,\'%Y-%m-%d\') as endtime,school,major,degree,major_code,degree_code,content FROM ResumeEdu WHERE resumeid = ? order by id';
        $var = [$resumeId];
        $result = Db::connect('jyrpo')->select($sql, $var);
        if (!empty($result)) {
            foreach ($result as $item => &$value) {
                if ($value['starttime'] == '0000-00-00') {
                    $value['starttime'] = '';
                }
                if ($value['endtime'] == '0000-00-00') {
                    $value['endtime'] = '';
                }
                if ($value['degree_code'] != '') {
                    $value['degree_code'] = $value['degree_code'] * 1;
                }

            }
            $dataAfter = array_merge($dataAfter, ['educationinfo' => $result]);
        }

        $sql = 'SELECT innerid,    innerupdatetime,  gender,    nation,           idcard,         politic,
                                       phone,       email,       age,           DATE_FORMAT(birthday,\'%Y-%m-%d\') as birthday,         cname,          workyear,    hukou,         area,
                                       expectarea,  salaryfrom,  salaryto,      expectsalaryfrom, expectsalaryto, degree,      major,         position,
                                       workindustry,career,      married,       school,           nofocuse,       skillinfo,   awardinfo,     selfintro,
                                       otherinfo,   hasworkinfo, hasprojectinfo,haseducationinfo, creator,        updator,    
                                       trimcname,   jobterm,       situation,        entrytime,      headpath 
                                       FROM RpoResume WHERE resumeid = ?';
        $var = [$resumeId];
        $result = Db::connect('jyrpo')->selectOne($sql, $var);

        if ($result['degree'] != '') {
            $result['degree'] = $result['degree'] * 1;
        }
        if ($result['gender'] != '') {
            $result['gender'] = $result['gender'] * 1;
        }
        if ($result['married'] != '') {
            $result['married'] = $result['married'] * 1;
        }
        if ($result['salaryfrom'] != '') {
            $result['salaryfrom'] = $result['salaryfrom'] * 1;
        }
        if ($result['salaryto'] != '') {
            $result['salaryto'] = $result['salaryto'] * 1;
        }
        if ($result['expectsalaryfrom'] != '') {
            $result['expectsalaryfrom'] = $result['expectsalaryfrom'] * 1;
        }

        if ($result['expectsalaryto'] != '') {
            $result['expectsalaryto'] = $result['expectsalaryto'] * 1;
        }

        $dataAfter = array_merge($dataAfter, $result);

        $sql = "SELECT accountid51job,userid51job,MobilePhone,Company,CurrSalaryFrom,CurrSalaryTo,ExpSalaryFrom,ExpSalaryTo FROM s_manager WHERE userid51job = ?";
        $var = [$resumeId];
        $result = Db::connect('jyrpo_oracle')->selectOne($sql, $var);

        $dataAfter = array_merge($dataAfter, $result);
        $dataAfterTmp = json_encode($dataAfter);
        $dataAfter = json_decode(strtolower($dataAfterTmp), true);
//        var_dump($dataAfter);


        if ($result['currsalaryfrom'] != '') {
            $result['currsalaryfrom'] = $result['currsalaryfrom'] * 1;
        }
        if ($result['currsalaryto'] != '') {
            $result['currsalaryto'] = $result['currsalaryto'] * 1;
        }
        if ($result['expsalaryfrom'] != '') {
            $result['expsalaryfrom'] = $result['expsalaryfrom'] * 1;
        }
        if ($result['expsalaryto'] != '') {
            $result['expsalaryto'] = $result['expsalaryto'] * 1;
        }

        $dataAfter = array_merge($dataAfter, $result);
//      var_dump($dataAfter);

        $diff = [];
        $diffArr = [];
        $resumeNewStr = json_encode($dataAfter, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PARTIAL_OUTPUT_ON_ERROR);

        //var_dump($dataBeforeStr);
        //var_dump($resumeNewStr);
//        file_put_contents($fileProfix . '/success/1.txt.json', $resumeNewStr);

        $this->arrayCompare($dataBefore, $dataAfter, $diff);
        if (!empty($diff)) {
            $diffArr = end($diff);//var_dump($diffArr);
        }

        $filePath = $fileProfix . 'success/' . floor($resumeId / 2000) . '/' . $resumeId . '_' . $taskId . '.txt';
        $fileStr = file_get_contents($filePath);

        $filePath = $fileProfix . 'success/' . floor($resumeId / 2000) . '/' . $resumeId . '_' . $taskId . '.json';
        $mlStr = file_get_contents($filePath);


        $result['dataBefore'] = $dataBeforeStr;
        $result['resumeNew'] = $resumeNewStr;
        $result['fileStr'] = $fileStr;
        $result['mlStr'] = $mlStr;
        $result['diffArr'] = $diffArr;
        return $result;
    }

    /**
     * 递归对两个结构相同的多维数组进行比较，并返回差值
     * @param array $array_1 存入时的数据
     * @param array $array_2 存入后的数据
     * @param $test  返回数组不同的部分（最后一位带键值）
     * @return array
     */
    public function arrayCompare(array $array_1, array $array_2, &$diff) {
        $result = [];
        foreach ($array_1 as $item => $value) {
            if (in_array($item, array('accountid51job', 'userid51job', 'relationaccid', 'profile'))) {
                continue;
            }
            if (!is_array($array_1[$item])) {
                if ($array_2[$item] == '0000-00-00' && $array_1[$item] == '') {
                    continue;
                }
                if ($array_2[$item] != $value) {
                    $tmp = [$item => [
                        $item . '_before' => $value,
                        $item . '_after' => $array_2[$item]]
                    ];
                    $result[$item] = $tmp;
                }
            }
            if (is_array($array_1[$item])) {
                if ($item == 'workinfo') {//比较工作信息
                    $workInfo = $this->compareWorkInfo($array_1[$item], $array_2[$item]);
                    if (!empty($workInfo)) {
                        $result[$item] = $workInfo;
                    }
                }
                if ($item == 'projectinfo') {//比较项目信息
                    $projectInfo = $this->compareProjectInfo($array_1[$item], $array_2[$item]);
                    if (!empty($projectInfo)) {
                        $result[$item] = $projectInfo;
                    }
                }
                if ($item == 'educationinfo') {//比较教育经历
                    $educationInfo = $this->compareEduInfo($array_1[$item], $array_2[$item]);
                    if (!empty($educationInfo)) {
                        $result[$item] = $educationInfo;
                    }
                }

            }
        }
        if (!empty($result)) $diff[] = $result;
        return $result;
    }

    /**
     * 比较工作经历信息，如果同一段工作经历发生变化，展示变化前后的数据
     * 如果有新增或删减工作经历，展示新增或删减的工作经历
     * @param $array_1 存入前的数据
     * @param $array_2 存入后的数据
     * @return array
     */
    protected function compareWorkInfo($array_1, $array_2) {
        $diffArr = [];
        foreach ($array_1 as $company_1) {
            $comp_1_Exist = false;
            foreach ($array_2 as &$company_2) {
                if ($company_2['starttime'] == '0000-00-00') {
                    $company_2['starttime'] = '';
                }
                if ($company_2['endtime'] == '0000-00-00') {
                    $company_2['endtime'] = '';
                }
                if ($company_1['company'] == $company_2['company']
                    && $company_1['starttime'] == $company_2['starttime']
                    && $company_1['endtime'] == $company_2['endtime']) {
                    $comp_1_Exist = true;
                    foreach ($company_1 as $key => $value) {
                        if ($company_2[$key] != $value) {
                            $diffArr[] = [
                                'before' => $company_1,
                                'after' => $company_2
                            ];
                        }
                    }
                }
            }
            unset($company_2);
            if (!$comp_1_Exist) {
                $diffArr[] = ['before' => $company_1,
                    'after' => null];
            }
        }

        foreach ($array_2 as $company_2) {
            $comp_2_Exist = false;
            foreach ($array_1 as $company_1) {
                if ($company_1['company'] == $company_2['company']
                    && $company_1['starttime'] == $company_2['starttime']
                    && $company_1['endtime'] == $company_2['endtime']) {
                    $comp_2_Exist = true;
                    break;
                }
            }
            if (!$comp_2_Exist) {
                $diffArr[] = ['before' => null,
                    'after' => $company_2];
            }
        }
        return $diffArr;
    }

    /**
     * 比较项目经验信息，如果同一段项目经验发生变化，展示变化前后的数据
     * 如果有新增或删减项目经验，展示新增或删减的项目经验
     * @param $array_1 存入前的数据
     * @param $array_2 存入后的数据
     * @return array
     */
    protected function compareProjectInfo($array_1, $array_2) {
        $diffArr = [];
        foreach ($array_1 as $project_1) {
            $pro_1_Exist = false;
            foreach ($array_2 as &$project_2) {
                if ($project_2['starttime'] == '0000-00-00') {
                    $project_2['starttime'] = '';
                }
                if ($project_2['endtime'] == '0000-00-00') {
                    $project_2['endtime'] = '';
                }
                if ($project_1['company'] == $project_2['company']
                    && $project_1['project'] == $project_2['project']
                    && $project_1['starttime'] == $project_2['starttime']
                    && $project_1['endtime'] == $project_2['endtime']) {
                    $pro_1_Exist = true;
                    foreach ($project_1 as $key => $value) {
                        if ($project_2[$key] != $value) {
                            $diffArr[] = [
                                'before' => $project_1,
                                'after' => $project_2
                            ];
                        }
                    }
                }
            }
            unset($project_2);
            if (!$pro_1_Exist) {
                $diffArr[] = ['before' => $project_1,
                    'after' => null];
            }
        }

        foreach ($array_2 as $project_2) {
            $pro_2_Exist = false;
            foreach ($array_1 as $project_1) {
                if ($project_1['company'] == $project_2['company']
                    && $project_1['project'] == $project_2['project']
                    && $project_1['starttime'] == $project_2['starttime']
                    && $project_1['endtime'] == $project_2['endtime']) {
                    $pro_2_Exist = true;
                    break;
                }
            }
            if (!$pro_2_Exist) {
                $diffArr[] = ['before' => null,
                    'after' => $project_2];
            }
        }
        return $diffArr;
    }

    /**
     * 比较教育经历信息，如果同一段教育经历发生变化，展示变化前后的数据
     * 如果有新增或删减教育经历，展示新增或删减的教育经历
     * @param $array_1 存入前的数据
     * @param $array_2 存入后的数据
     * @return array
     */
    protected function compareEduInfo($array_1, $array_2) {
        $diffArr = [];
        foreach ($array_1 as $edu_1) {
            $edu_1_Exist = false;
            foreach ($array_2 as &$edu_2) {
                if ($edu_2['starttime'] == '0000-00-00') {
                    $edu_2['starttime'] = '';
                }
                if ($edu_2['endtime'] == '0000-00-00') {
                    $edu_2['endtime'] = '';
                }
                if ($edu_1['school'] == $edu_2['school']
                    && $edu_1['major'] == $edu_2['major']
                    && $edu_1['degree'] == $edu_2['degree']
                    && $edu_1['starttime'] == $edu_2['starttime']
                    && $edu_1['endtime'] == $edu_2['endtime']) {
                    $edu_1_Exist = true;
                    foreach ($edu_1 as $key => $value) {
                        if ($edu_2[$key] != $value) {
                            $diffArr[] = [
                                'before' => $edu_1,
                                'after' => $edu_2
                            ];
                        }
                    }
                }
            }
            unset($edu_2);
            if (!$edu_1_Exist) {
                $diffArr[] = ['before' => $edu_1,
                    'after' => null];
            }
        }

        foreach ($array_2 as $edu_2) {
            $edu_2_Exist = false;
            foreach ($array_1 as $edu_1) {
                if ($edu_1['school'] == $edu_2['school']
                    && $edu_1['major'] == $edu_2['major']
                    && $edu_1['degree'] == $edu_2['degree']
                    && $edu_1['starttime'] == $edu_2['starttime']
                    && $edu_1['endtime'] == $edu_2['endtime']) {
                    $edu_2_Exist = true;
                    break;
                }
            }
            if (!$edu_2_Exist) {
                $diffArr[] = ['before' => null,
                    'after' => $edu_2];
            }
        }
        return $diffArr;
    }
}